package com.rabbitmq.spring.api;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import static com.rabbitmq.common.constants.CommonConstants.UTF_8;

/**
 * @author
 * @Describe 消息监听器，所有设置得队列的消息处理都统一处理
 * @date
 */
@Component
@Slf4j(topic = "ManualAckMessageListener")
public class ManualAckMessageListener implements ChannelAwareMessageListener {
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        MessageProperties messageProperties = message.getMessageProperties();
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            log.info(" ===== onMessage msg is {} ===== ", new String(message.getBody(), UTF_8));
            log.info(" ===== onMessage receivedExchange is {} ===== ", messageProperties.getReceivedExchange());
            log.info(" ===== onMessage receivedRoutingKey is {} ===== ", messageProperties.getReceivedRoutingKey());
            log.info(" ===== onMessage consumerQueue is {} ===== ", messageProperties.getConsumerQueue());
            // 第二个参数，手动确人是否可以多个处理，当该参数为 true 时，则可以一次性确认 delivery_tag 小于等于传入值的所有消息
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            log.error(" onMessage异常", e);
            // 第二个参数，true会重新放回队列，所以需要自己根据业务逻辑判断什么时候使用拒绝，慎用
            channel.basicReject(deliveryTag, false);
        }
    }
}
